﻿using System.Linq;

namespace LetsDoItWS.BO
{
    /// <summary>
    /// authentication factory class
    /// </summary>
    public class AuthenticationFactory
    {
        /// <summary>
        /// Validate user based on name and md5 hashed password
        /// </summary>
        /// <param name="user">user name</param>
        /// <param name="passwordMD5">md5 hashed pass(contains "salt" also)</param>
        /// <returns></returns>
        public static int ValidateUser(string user, string passwordMD5)
        {
            int count = 0;
            using (ldirdbEntities dataContext = new ldirdbEntities())
            {
                User userInfo = dataContext.Users.FirstOrDefault(u => u.username == user);
                if (userInfo != null)
                {
                    string[] passdb = userInfo.password.Split(':');
                    if (passdb.Count() > 0)
                    {
                        string salt = passdb.Count() > 1 ? passdb[1] : string.Empty;
                        string passtoCheck = passwordMD5 + ":" + salt;
                        count = dataContext.Users.Count(u => u.username == user && u.password == passtoCheck);
                    }
                }
            }
            return count;
        }

        /// <summary>
        /// Get user "salt" string
        /// </summary>
        /// <param name="user">user name</param>
        /// <returns>"salt" string</returns>
        public static string GetUserSalt(string user)
        {
            string salt = string.Empty;
            using (ldirdbEntities dataContext = new ldirdbEntities())
            {
                User userInfo = dataContext.Users.FirstOrDefault(u => u.username == user);
                if (userInfo != null)
                {
                    string[] passdb = userInfo.password.Split(':');
                    salt = passdb.Count() > 1 ? passdb[1] : string.Empty;
                }
            }

            return salt;
        }
    }
}